package com.njtoyo.taxi.admin.service.open.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.njtoyo.taxi.admin.aop.YDException;
import com.njtoyo.taxi.admin.cache.PrimaryCachePutter;
import com.njtoyo.taxi.admin.library.common.GeoPoint;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.logic.business.TaxisLogic;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverCustomMessageEventCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverCustomMessageLinkCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.MemberCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mapper.secondary.entity.DriverRegisterForm;
import com.njtoyo.taxi.admin.rest.pojo.dto.DriverTaxiVehicleInfo;
import com.njtoyo.taxi.admin.service.open.DriverRegisterService;
import com.taxi.entity.common.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.matches;

@Service
@Slf4j
public class DriverRegisterServiceImpl implements DriverRegisterService {

    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private GeoCantonMapper geoCantonMapper;
    @Autowired
    private GeoDriverRegionMapper driverRegionMapper;
    @Autowired
    private TaxiMapper taxiMapper;
    @Autowired
    private TaxisLogic taxisBatchLogic;
    @Autowired
    private TaxiLastLocateMapper taxiLastLocateMapper;
    @Autowired
    private PrimaryCachePutter primaryCachePutter;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverExtraInformationMapper driverExtraInformationMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private DriverCustomMessageMapper driverCustomMessageMapper;
    @Autowired
    private OperationRecordHelper operationRecordHelper;
    @Autowired
    private DriverTaxiRelationMapper driverTaxiRelationMapper;
    @Autowired
    private TaxiCallRelationMapper taxiCallRelationMapper;
    @Autowired
    private RegionCallRelationMapper regionCallRelationMapper;

    @Override
    public RestResult getCityList(String cityName) {
        LambdaQueryWrapper<City> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(cityName)) {
            queryWrapper.like(City::getName, cityName);
        }
        List<City> cities = cityMapper.selectList(queryWrapper);
        return RestResult.success(cities);
    }

    @Override
    public RestResult getCompany(String companyName) {
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(companyName)) {
            queryWrapper.like(Company::getName, companyName);
        }
        List<Company> list = companyMapper.selectList(queryWrapper);
        return RestResult.success(list);
    }

    @Override
    public RestResult getCanton(String cantonName) {
        LambdaQueryWrapper<GeoCanton> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(cantonName)) {
            queryWrapper.like(GeoCanton::getName, cantonName);
        }
        List<GeoCanton> list = geoCantonMapper.selectList(queryWrapper);
        return RestResult.success(list);
    }

    /**
     * 注册司机
     *
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult add(DriverRegisterForm form) {
        log.info("开始注册司机,参数：{}", JSON.toJSONString(form));
        Long driverRegionId = driverRegionMapper.getRegionIdByAdCode(form.getAdCode());
        Company company = companyMapper.selectOne(Wrappers.<Company>lambdaQuery()
                .eq(Company::getDriverRegionId, driverRegionId)
                .like(Company::getName, "有滴出行")
                .last("limit 1"));
        if (Objects.isNull(company)) {
            log.info("未找到公司信息,使用默认的公司");
            company = companyMapper.selectById(39L);
        }
        Long taxiId = null;
        Long vehicleModelId = null;
        if (form.getType() == 1) {//注册网约车
            DriverExtraInformation driverExtraInformation = driverExtraInformationMapper.selectOne(Wrappers.<DriverExtraInformation>lambdaQuery()
                    .eq(DriverExtraInformation::getIdentityNumber, form.getIdentityNumber()));
            if (ObjectUtil.isNotNull(driverExtraInformation)) {//司机已存在 老司机的处理流程
                List<DriverTaxiVehicleInfo> taxiList = driverMapper.getBindTaxiInfoByDriverId(driverExtraInformation.getDriverId());
                Boolean isTaxi = false;
                Boolean isRideHailingTaxi = false;
                Boolean isRideHailing = false;
                for (DriverTaxiVehicleInfo taxi : taxiList) {
                    if ("ride-hailing".equals(taxi.getVehicleModelCode())) {//网约车
                        isRideHailing = true;
                    } else if ("ride-hailing-taxi".equals(taxi.getVehicleModelCode())) {//巡游出租车
                        isRideHailingTaxi = true;
                    } else if ("taxi".equals(taxi.getVehicleModelCode())) {//出租车
                        isTaxi = true;
                    }
                }
                if (isRideHailing || isRideHailingTaxi) {
                    throw new YDException("司机已经是网约车司机,请先解绑");
                } else {//没有绑过网约车
                    Optional<DriverTaxiVehicleInfo> boundTaxiOpt = taxiList.stream()
                            .filter(taxi -> "taxi".equals(taxi.getVehicleModelCode()))
                            .findFirst();
                    DriverTaxiVehicleInfo boundTaxi = boundTaxiOpt.get();
                    String boundPlateNumber = boundTaxi.getPlateNumber();
                    // 判断提交表单的车牌号是否与已绑定的普通出租车车牌号相同
                    if (form.getTaxiPlatNumber().equals(boundPlateNumber)) {
                        log.info("提交的车牌号: {} 与已绑定的普通出租车车牌号: {} 相同，开始升级为网约车",
                                form.getTaxiPlatNumber(), boundPlateNumber);
                        Taxi updateTaxi = new Taxi();
                        updateTaxi.setId(boundTaxi.getTaxiId());
                        updateTaxi.setVehicleModel(3);
                        taxiMapper.updateById(updateTaxi);
                        vehicleModelId = 3L;
                        //添加绑定关系
                        DriverTaxiRelation driverTaxiRelation = driverTaxiRelationMapper.selectOne(Wrappers.<DriverTaxiRelation>lambdaQuery()
                                .eq(DriverTaxiRelation::getDriverId, driverExtraInformation.getDriverId())
                                .eq(DriverTaxiRelation::getTaxiId, updateTaxi.getId()));
                        if (ObjectUtil.isNull(driverTaxiRelation)) {
                            DriverTaxiRelation relation = new DriverTaxiRelation();
                            relation.setDriverId(driverExtraInformation.getDriverId());
                            relation.setTaxiId(boundTaxi.getTaxiId());
                            driverTaxiRelationMapper.insert(relation);
                        }
                        Driver driver = driverMapper.selectById(driverExtraInformation.getDriverId());
                        List<RegionCallRelation> regionCallRelations = regionCallRelationMapper.selectList(Wrappers.<RegionCallRelation>lambdaQuery()
                                .eq(RegionCallRelation::getDriverRegionId, driver.getDriverRegionId())
                                .eq(RegionCallRelation::getVehicleTypeId, vehicleModelId));
                        //TODO 绑定开通运营区所有接单类型
                        for (RegionCallRelation regionCallRelation : regionCallRelations) {
                            TaxiCallRelation taxiCallRelation = taxiCallRelationMapper.selectOne(Wrappers.<TaxiCallRelation>lambdaQuery()
                                    .eq(TaxiCallRelation::getTaxiId, boundTaxi.getTaxiId())
                                    .eq(TaxiCallRelation::getCallTypeId, regionCallRelation.getCallTypeId()));
                            if (ObjectUtil.isNull(taxiCallRelation)) {
                                TaxiCallRelation AddtaxiCallRelation = new TaxiCallRelation();
                                AddtaxiCallRelation.setCallTypeId(regionCallRelation.getCallTypeId());
                                AddtaxiCallRelation.setTaxiId(boundTaxi.getTaxiId());
                                taxiCallRelationMapper.insert(AddtaxiCallRelation);
                            }
                        }
                    } else {
                        log.info("提交的车牌号: {} 与已绑定的普通出租车车牌号: {} 不同，开始新出租车注册流程",
                                form.getTaxiPlatNumber(), boundPlateNumber);
                        Taxi taxi = taxiMapper.selectOne(Wrappers.<Taxi>lambdaQuery()
                                .eq(Taxi::getPlateNumber, form.getTaxiPlatNumber()));
                        if (ObjectUtil.isNull(taxi)) {
                            Taxi addTaxi = new Taxi();
                            addTaxi.setCompanyId(company.getId());
                            addTaxi.setType(form.getType());
                            addTaxi.setVehicleModel(1);
                            addTaxi.setSerialNumber(form.getSerialNumber());
                            addTaxi.setPlateNumber(form.getTaxiPlatNumber());
                            taxiMapper.insert(addTaxi);
                            taxiId = addTaxi.getId();
                            vehicleModelId = 1L;
                        } else {
                            Taxi updateTaxi = new Taxi();
                            updateTaxi.setId(taxi.getId());
                            if (taxi.getVehicleModel() == 2) {
                                updateTaxi.setVehicleModel(3);
                                vehicleModelId = 3L;
                            } else {
                                vehicleModelId = Convert.toLong(taxi.getVehicleModel());
                            }
                            taxiMapper.updateById(updateTaxi);
                            taxiId = updateTaxi.getId();
                        }
                        //添加绑定关系
                        DriverTaxiRelation driverTaxiRelation = driverTaxiRelationMapper.selectOne(Wrappers.<DriverTaxiRelation>lambdaQuery()
                                .eq(DriverTaxiRelation::getDriverId, driverExtraInformation.getDriverId())
                                .eq(DriverTaxiRelation::getTaxiId, taxiId));
                        if (ObjectUtil.isNull(driverTaxiRelation)) {
                            DriverTaxiRelation relation = new DriverTaxiRelation();
                            relation.setDriverId(driverExtraInformation.getDriverId());
                            relation.setTaxiId(taxiId);
                            driverTaxiRelationMapper.insert(relation);
                        }
                        Driver driver = driverMapper.selectById(driverExtraInformation.getDriverId());
                        List<RegionCallRelation> regionCallRelations = regionCallRelationMapper.selectList(Wrappers.<RegionCallRelation>lambdaQuery()
                                .eq(RegionCallRelation::getDriverRegionId, driver.getDriverRegionId())
                                .eq(RegionCallRelation::getVehicleTypeId, vehicleModelId));
                        //TODO 绑定开通运营区所有接单类型
                        for (RegionCallRelation regionCallRelation : regionCallRelations) {
                            TaxiCallRelation taxiCallRelation = taxiCallRelationMapper.selectOne(Wrappers.<TaxiCallRelation>lambdaQuery()
                                    .eq(TaxiCallRelation::getTaxiId, taxiId)
                                    .eq(TaxiCallRelation::getCallTypeId, regionCallRelation.getCallTypeId()));
                            if (ObjectUtil.isNull(taxiCallRelation)) {
                                TaxiCallRelation AddtaxiCallRelation = new TaxiCallRelation();
                                AddtaxiCallRelation.setCallTypeId(regionCallRelation.getCallTypeId());
                                AddtaxiCallRelation.setTaxiId(taxiId);
                                taxiCallRelationMapper.insert(AddtaxiCallRelation);
                            }
                        }
                    }
                }
            } else {//司机不存在
                //判断车牌号是否已注册
                Taxi taxi = taxiMapper.selectOne(Wrappers.<Taxi>lambdaQuery().eq(Taxi::getPlateNumber, form.getTaxiPlatNumber()));
                if (ObjectUtil.isNotNull(taxi)) {//车牌号已存在
                    //判断车辆是否是网约车
                    if (taxi.getVehicleModel() == 1) {
                        vehicleModelId = 1L;
                        taxiId = taxi.getId();
                        //注册司机
                        Driver driver = registerOnlineDriver(form, taxi);
                        Long id = driver.getId();
                        //添加绑定关系
                        DriverTaxiRelation driverTaxiRelation = driverTaxiRelationMapper.selectOne(Wrappers.<DriverTaxiRelation>lambdaQuery()
                                .eq(DriverTaxiRelation::getDriverId, driver.getId())
                                .eq(DriverTaxiRelation::getTaxiId, taxiId));
                        if (ObjectUtil.isNull(driverTaxiRelation)) {
                            DriverTaxiRelation relation = new DriverTaxiRelation();
                            relation.setDriverId(driver.getId());
                            relation.setTaxiId(taxiId);
                            driverTaxiRelationMapper.insert(relation);
                        }
                        List<RegionCallRelation> regionCallRelations = regionCallRelationMapper.selectList(Wrappers.<RegionCallRelation>lambdaQuery()
                                .eq(RegionCallRelation::getDriverRegionId, driver.getDriverRegionId())
                                .eq(RegionCallRelation::getVehicleTypeId, vehicleModelId));
                        //TODO 绑定开通运营区所有接单类型
                        for (RegionCallRelation regionCallRelation : regionCallRelations) {
                            TaxiCallRelation taxiCallRelation = taxiCallRelationMapper.selectOne(Wrappers.<TaxiCallRelation>lambdaQuery()
                                    .eq(TaxiCallRelation::getTaxiId, taxiId)
                                    .eq(TaxiCallRelation::getCallTypeId, regionCallRelation.getCallTypeId()));
                            if (ObjectUtil.isNull(taxiCallRelation)) {
                                TaxiCallRelation AddtaxiCallRelation = new TaxiCallRelation();
                                AddtaxiCallRelation.setCallTypeId(regionCallRelation.getCallTypeId());
                                AddtaxiCallRelation.setTaxiId(taxiId);
                                taxiCallRelationMapper.insert(AddtaxiCallRelation);
                            }
                        }
                    } else {
                        return RestResult.failed("该车辆不是网约车无法绑定");
                    }
                } else {//车牌号不存在 注册成功后成为网约车司机
                    Taxi addTaxi = new Taxi();
                    addTaxi.setCompanyId(company.getId());
                    addTaxi.setType(form.getType());
                    addTaxi.setVehicleModel(1);
                    addTaxi.setSerialNumber(form.getSerialNumber());
                    addTaxi.setPlateNumber(form.getTaxiPlatNumber());
                    taxiMapper.insert(addTaxi);
                    taxiId = addTaxi.getId();

                    //注册司机
                    Driver driver = registerOnlineDriver(form, addTaxi);
                    //添加绑定关系
                    DriverTaxiRelation driverTaxiRelation = driverTaxiRelationMapper.selectOne(Wrappers.<DriverTaxiRelation>lambdaQuery()
                            .eq(DriverTaxiRelation::getDriverId, driver.getId())
                            .eq(DriverTaxiRelation::getTaxiId, taxiId));
                    if (ObjectUtil.isNull(driverTaxiRelation)) {
                        DriverTaxiRelation relation = new DriverTaxiRelation();
                        relation.setDriverId(driver.getId());
                        relation.setTaxiId(taxiId);
                        driverTaxiRelationMapper.insert(relation);
                    }
                    List<RegionCallRelation> regionCallRelations = regionCallRelationMapper.selectList(Wrappers.<RegionCallRelation>lambdaQuery()
                            .eq(RegionCallRelation::getDriverRegionId, driver.getDriverRegionId())
                            .eq(RegionCallRelation::getVehicleTypeId, 1l));
                    //TODO 绑定开通运营区所有接单类型
                    for (RegionCallRelation regionCallRelation : regionCallRelations) {
                        TaxiCallRelation taxiCallRelation = taxiCallRelationMapper.selectOne(Wrappers.<TaxiCallRelation>lambdaQuery()
                                .eq(TaxiCallRelation::getTaxiId, taxiId)
                                .eq(TaxiCallRelation::getCallTypeId, regionCallRelation.getCallTypeId()));
                        if (ObjectUtil.isNull(taxiCallRelation)) {
                            TaxiCallRelation AddtaxiCallRelation = new TaxiCallRelation();
                            AddtaxiCallRelation.setCallTypeId(regionCallRelation.getCallTypeId());
                            AddtaxiCallRelation.setTaxiId(taxiId);
                            taxiCallRelationMapper.insert(AddtaxiCallRelation);
                        }
                    }
                }

            }
        } else {//注册非网约车
            //校验车牌号,发动机号
            String pattern = "[测京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][A-Za-z0-9]+";
            boolean flag = matches(pattern, form.getTaxiPlatNumber());
            if (!flag) {
                throw new YDException("车牌号码格式错误");
            }
            if (ObjectUtils.isEmpty(form.getSerialNumber())) {
                throw new YDException("发动机号不能为空");
            }
            Taxi taxi = new Taxi();
            Integer count = taxiMapper.selectPlateNumber(form.getTaxiPlatNumber());
            if (count >= 1) {
                throw new YDException("注册失败,车牌号已存在");
            }
            taxi.setCompanyId(company.getId());
            taxi.setType(form.getType());
            taxi.setSerialNumber(form.getSerialNumber());
            taxi.setPlateNumber(form.getTaxiPlatNumber());
            taxiMapper.insert(taxi);
            Long id = taxi.getId();
            operationRecordHelper.addBusinessLog(String.format("自主注册了车辆 [%d] 的车牌号为 %s 的信息", id, form.getTaxiPlatNumber()));

            taxiLastLocateMapper.insert(new TaxiLastLocate().setTaxiId(id).setCreatedAt(DateUtil.date()).setPoint(new GeoPoint(new Double(0.0), new Double(0.0))));


            //注册司机信息
            RestResult result = registerDriver(form);
            if (ObjectUtil.isNotNull(result)) {
                return result;
            }
        }
        return RestResult.success();
    }

    private Driver registerOnlineDriver(DriverRegisterForm form, Taxi taxi) {
        // 姓名
        if (Objects.isNull(form.getDriverName())) {
            throw new YDException("姓名不能为空");
        }
        // 判断手机号
        if (Objects.isNull(form.getMobileNumber()) || !Pattern.matches("^1[0-9]{10}$", form.getMobileNumber())) {
            throw new YDException("手机号格式不正确");
        }
        // 判断车牌
        if (Objects.isNull(form.getTaxiPlatNumber()) || !Pattern.matches("[测京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][A-Za-z0-9]+", form.getTaxiPlatNumber())) {
            throw new YDException("车牌号格式不正确");
        }
        // 手机号是否重复
        QueryWrapper<Driver> driverWrapper = new QueryWrapper<>();
        driverWrapper.eq("mobile_number", form.getMobileNumber());
        if (driverMapper.selectCount(driverWrapper) > 0 && form.getType() == 1) {
            throw new YDException("号码已存在");
        }
        // 公司信息
        Long driverRegionId = driverRegionMapper.getRegionIdByAdCode(form.getAdCode());
        Company company = companyMapper.selectOne(Wrappers.<Company>lambdaQuery()
                .eq(Company::getDriverRegionId, driverRegionId)
                .like(Company::getName, "有滴出行")
                .last("limit 1"));

        if (Objects.isNull(company)) {
            log.info("未找到公司信息,使用默认的公司");
            company = companyMapper.selectById(39L);
        }

        // 判断身份证号长度
        if (Objects.nonNull(form.getIdentityNumber()) && form.getIdentityNumber().length() != 18) {
            throw new YDException("身份证号格式不正确");
        }
        DriverExtraInformation driverExtraInformation = driverExtraInformationMapper.selectOne(Wrappers.<DriverExtraInformation>lambdaQuery().eq(DriverExtraInformation::getIdentityNumber, form.getIdentityNumber()));
        if (ObjectUtil.isNotNull(driverExtraInformation)) {
            throw new YDException("身份证号已存在,不能重复添加！");
        }

        // 判断是否有额外信息
        boolean hasExtra = Objects.nonNull(form.getIdentityNumber()) || Objects.nonNull(form.getQualificationCertificateNumber());


        // 添加司机信息
        Driver driver = new Driver();
        driver.setName(form.getDriverName())
                .setMobileNumber(form.getMobileNumber())
                .setPassword(SecureUtil.md5(form.getMobileNumber().substring(5) + "@yd"))
                .setAvatarUrl("https://store.jjtoyo.com/driver/driver-head.png")
                .setLocateCityId(form.getCityId())
                .setDriverRegionId(driverRegionId)
                .setCantonId(company.getCantonId())
                .setIsActive(true).setTaxiId(taxi.getId());
        driverMapper.insert(driver);
        log.info("插入司机信息 {}", driver);
        // 添加会员信息
        Member member = new Member();
        member.setCategory(MemberCategory.driver).setRefId(driver.getId());
        memberMapper.insert(member);
        log.info("插入会员信息 {}", member);
        // 司机消息
        DriverCustomMessage message = new DriverCustomMessage();
        message.setDriverId(driver.getId()).setContent("欢迎使用巡网融合出行平台，优质派单、安全出行。").setIsPlainText(true).setLinkCategory(DriverCustomMessageLinkCategory.self).setEventCategory(DriverCustomMessageEventCategory.system).setIsRead(false);
        driverCustomMessageMapper.insert(message);
        log.info("插入司机消息 {}", message);

        // 如果存在额外信息，则插入
        if (hasExtra) {
            DriverExtraInformation extra = new DriverExtraInformation();
            extra.setDriverId(driver.getId());

            if (ObjectUtil.isNotEmpty(form.getIdentityNumber())) {
                extra.setIdentityNumber(form.getIdentityNumber());
            }


            if (ObjectUtil.isNotEmpty(form.getQualificationCertificateNumber())) {
                extra.setQualificationCertificateNumber(form.getQualificationCertificateNumber());
            }

            driverExtraInformationMapper.insert(extra);
            log.info("插入司机额外消息 {}", extra);
        }
        primaryCachePutter.deleteDriverMobile(form.getMobileNumber());
        return driver;
    }


    private RestResult registerDriver(DriverRegisterForm form) {
        // 姓名
        if (Objects.isNull(form.getDriverName())) {
            throw new YDException("姓名不能为空");
        }
        // 判断手机号
        if (Objects.isNull(form.getMobileNumber()) || !Pattern.matches("^1[0-9]{10}$", form.getMobileNumber())) {
            throw new YDException("手机号格式不正确");
        }
        // 判断车牌
        if (Objects.isNull(form.getTaxiPlatNumber()) || !Pattern.matches("[测京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][A-Za-z0-9]+", form.getTaxiPlatNumber())) {
            throw new YDException("车牌号格式不正确");
        }
        // 手机号是否重复
        QueryWrapper<Driver> driverWrapper = new QueryWrapper<>();
        driverWrapper.eq("mobile_number", form.getMobileNumber());
        if (driverMapper.selectCount(driverWrapper) > 0) {
            throw new YDException("号码已存在");
        }
        // 车俩信息
        QueryWrapper<Taxi> taxiWrapper = new QueryWrapper<>();
        taxiWrapper.eq("plate_number", form.getTaxiPlatNumber());
        Taxi taxi = taxiMapper.selectOne(taxiWrapper);
        if (Objects.isNull(taxi)) {
            throw new YDException("车俩不存在");
        }
        if (taxi.getIsScrapped()) {
            throw new YDException("车俩已经报废");
        }
        // 公司信息
        Company company = companyMapper.selectById(taxi.getCompanyId());
        if (Objects.isNull(company)) {
            throw new YDException("车俩对应公司不存在");
        }

        // 判断身份证号长度
        if (Objects.nonNull(form.getIdentityNumber()) && form.getIdentityNumber().length() != 18) {
            throw new YDException("身份证号格式不正确");
        }
        DriverExtraInformation driverExtraInformation = driverExtraInformationMapper.selectOne(Wrappers.<DriverExtraInformation>lambdaQuery().eq(DriverExtraInformation::getIdentityNumber, form.getIdentityNumber()));
        if (ObjectUtil.isNotNull(driverExtraInformation)) {
            throw new YDException("身份证号已存在,不能重复添加！");
        }

        // 判断是否有额外信息
        boolean hasExtra = Objects.nonNull(form.getIdentityNumber()) || Objects.nonNull(form.getQualificationCertificateNumber());

        // 添加司机信息
        Driver driver = new Driver();
        driver.setName(form.getDriverName()).setMobileNumber(form.getMobileNumber()).setPassword(SecureUtil.md5(form.getMobileNumber().substring(5) + "@yd")).setAvatarUrl("https://store.jjtoyo.com/driver/driver-head.png").setLocateCityId(form.getCityId()).setDriverRegionId(company.getDriverRegionId()).setCantonId(company.getCantonId()).setIsActive(true).setTaxiId(taxi.getId());
        driverMapper.insert(driver);
        log.info("插入司机信息 {}", driver);
        // 添加会员信息
        Member member = new Member();
        member.setCategory(MemberCategory.driver).setRefId(driver.getId());
        memberMapper.insert(member);
        log.info("插入会员信息 {}", member);
        // 司机消息
        DriverCustomMessage message = new DriverCustomMessage();
        message.setDriverId(driver.getId()).setContent("欢迎使用巡网融合出行平台，优质派单、安全出行。").setIsPlainText(true).setLinkCategory(DriverCustomMessageLinkCategory.self).setEventCategory(DriverCustomMessageEventCategory.system).setIsRead(false);
        driverCustomMessageMapper.insert(message);
        log.info("插入司机消息 {}", message);

        // 如果存在额外信息，则插入
        if (hasExtra) {
            DriverExtraInformation extra = new DriverExtraInformation();
            extra.setDriverId(driver.getId());

            if (ObjectUtil.isNotEmpty(form.getIdentityNumber())) {
                extra.setIdentityNumber(form.getIdentityNumber());
            }


            if (ObjectUtil.isNotEmpty(form.getQualificationCertificateNumber())) {
                extra.setQualificationCertificateNumber(form.getQualificationCertificateNumber());
            }

            driverExtraInformationMapper.insert(extra);
            log.info("插入司机额外消息 {}", extra);
        }
        primaryCachePutter.deleteDriverMobile(form.getMobileNumber());
        return null;
    }
}
